// src/components/scholarDashboard/mainContent/MainContentSection.tsx

import { useState, useEffect, useCallback, useRef } from 'react';
import Headline from '@/components/scholarDashboard/header/Headline';
import DashboardTabs from '@/components/scholarDashboard/mainContent/DashboardTabs';
import Table from '@/components/scholarDashboard/mainContent/Table';
import Pagination from '@/components/scholarDashboard/mainContent/Pagination';
import Overview from '@/components/scholarDashboard/mainContent/Overview';
import ColumnSelector from '@/components/scholarDashboard/mainContent/ColumnSelector';
import { fetchScholarRecords, transformScholarRecords, type ScholarRecordWithFullName } from '@/services/scholarsDashboardService/tableScholarRecords';
import { searchScholars } from '@/services/scholarsDashboardService/tableSearchScholars';
import { useDashboardTabStore } from '@/store/dashboardTabStore';
import { usePermissions } from '@/utils/permissionUtils';

const MainContentSection = () => {
  const { canViewScholarsDashboardContent } = usePermissions();
  const { currentTab } = useDashboardTabStore();
  const [searchText, setSearchText] = useState('');
  const [startDate, setStartDate] = useState<string>('');
  const [endDate, setEndDate] = useState<string>('');
  const [scholars, setScholars] = useState<ScholarRecordWithFullName[]>([]);
  const [loading, setLoading] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [hasSearched, setHasSearched] = useState(false);
  const pageSize = 10;

  const searchTextRef = useRef(searchText);
  const startDateRef = useRef(startDate);
  const endDateRef = useRef(endDate);

  useEffect(() => {
    searchTextRef.current = searchText;
    startDateRef.current = startDate;
    endDateRef.current = endDate;
  }, [searchText, startDate, endDate]);

  const allHeaders = [
    { key: "student_number", label: "Student Number" },
    { key: "program", label: "Program ID" },
    { key: "full_name", label: "Full Name" },
    { key: "preferred_name", label: "Preferred Name" },
    { key: "default_email", label: "Student Email" },
    { key: "alternate_email", label: "Alternate Email" },
    { key: "scholar_type", label: "Scholar Type" },
    { key: "year", label: "Year" },
    { key: "university_status", label: "University Status" },
    { key: "date_of_birth", label: "Date of Birth" },
    { key: "gender", label: "Gender" },
    { key: "school_code", label: "School Code" },
    { key: "school_name", label: "School Name" },
    { key: "gateway_school", label: "Gateway School" },
    { key: "indigenous_student", label: "Indigenous Student" },
    { key: "start_date", label: "Start Date" },
    { key: "end_date", label: "End Date" },
    { key: "dietary_preference", label: "Dietary Preference" },
    { key: "dietary_allergies", label: "Dietary Allergies" },
    { key: "dietary_religious", label: "Dietary Religious" },
    { key: "medical_allergies", label: "Medical Allergies" },
    { key: "ite_number", label: "ITE Number" },
    { key: "sponsor_name", label: "Sponsor Name" },
    { key: "department", label: "Department" },
    { key: "supervisors", label: "Supervisor Name(Title)" },
    { key: "ite_start", label: "ITE Start" },
    { key: "ite_end", label: "ITE End" },
    { key: "ite_details_input_date", label: "ITE Details Input Date" },
    { key: "ite_input_in_time", label: "ITE Input In Time" },
    { key: "latest_start_date", label: "Latest Start Date" },
    { key: "expected_finish_date", label: "Expected Finish Date" },
    { key: "start_date_met", label: "Start Date Met" },
    { key: "end_date_met", label: "End Date Met" },
    { key: "it_change_approved", label: "IT Change Approved" },
    { key: "pd_agreement_submission_date", label: "PD Agreement Submission Date" },
    // { key: "pd_submitted_on_time", label: "PD Submitted On Time" },
    { key: "placement_mid_point", label: "Placement Mid Point" },
    { key: "mpc_call_date", label: "MPC Call Date" },
    { key: "mpc_call_on_time", label: "MPC Call On Time" },
    { key: "mpc_document_due_date", label: "MPC Document Due Date" },
    { key: "mpc_submitted_date", label: "MPC Submitted Date" },
    { key: "mpc_submitted_on_time", label: "MPC Submitted On Time" },
    { key: "end_of_it_presentation_date", label: "End of IT Presentation Date" },
    { key: "end_of_it_input_date", label: "End of IT Input Date" },
    { key: "it_presentation_completed_ontime", label: "IT Presentation Completed On Time" },
    { key: "unsw_attendee_on_presentation", label: "UNSW Attendee On Presentation" },
    { key: "sponsor_evaluation_sent_to_sponsor_date", label: "Sponsor Evaluation Sent To Sponsor Date" },
    { key: "sent_before_end_of_placement", label: "Sent Before End of Placement" },
    { key: "sponsor_completed_date", label: "Sponsor Completed Date" },
    { key: "scholar_comment", label: "Scholar Comment" },
    { key: "sponsor_evaluation_completed_on_time", label: "Sponsor Evaluation Completed On Time" },
    { key: "placement_completed_date", label: "Placement Completed Date" },
    { key: "placement_grade", label: "Placement Grade" },
    { key: "placement_performance", label: "Placement Performance" },
    { key: "grade_updated", label: "Grade Updated" },
    { key: "grade_updated_date", label: "Grade Updated Date" },
  ];

  const initialSelectedHeaders = [
    "student_number", "program", "year", "full_name", "preferred_name",
    "default_email", "alternate_email", "gender", "date_of_birth",
    "university_status", "start_date", "end_date", "scholar_type"
  ];

  const [selectedHeaders, setSelectedHeaders] = useState<string[]>(initialSelectedHeaders);

  const loadData = useCallback(async (page: number, keywords?: string, startDateInput?: string, endDateInput?: string) => {
    try {
      setLoading(true);
      const skip = (page - 1) * pageSize;

      const formatDate = (dateStr: string): string => {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return date.toISOString().slice(0, 10);
      };

      const formattedStartDate = startDateInput ? formatDate(startDateInput) : '';
      const formattedEndDate = endDateInput ? formatDate(endDateInput) : '';

      const hasSearchCriteria = (keywords && keywords.trim() !== '') ||
        (formattedStartDate && formattedStartDate.trim() !== '') ||
        (formattedEndDate && formattedEndDate.trim() !== '');

      if (hasSearchCriteria) {
        const response = await searchScholars({
          skip,
          limit: pageSize,
          keywords,
          start_date_input: formattedStartDate || undefined,
          end_date_input: formattedEndDate || undefined
        });
        setTimeout(() => {
          const transformedScholars = transformScholarRecords(response.scholars || []);
          setScholars(transformedScholars);
          setTotalCount(response.total || 0);
          setLoading(false);
        }, 200);
      } else {
        const response = await fetchScholarRecords({ skip, limit: pageSize });
        setTimeout(() => {
          const transformedScholars = transformScholarRecords(response.scholars || []);
          setScholars(transformedScholars);
          setTotalCount(response.total || 0);
          setLoading(false);
        }, 200);
      }
    } catch (err) {
      console.error('Failed to fetch scholar records:', err);
      setLoading(false);
    }
  }, [pageSize]);

  useEffect(() => {
    loadData(currentPage);
  }, [loadData, currentPage]);

  useEffect(() => {
    if (hasSearched) {
      loadData(currentPage, searchTextRef.current, startDateRef.current, endDateRef.current);
    } else {
      loadData(currentPage);
    }
  }, [currentPage, hasSearched, loadData]);

  const handleSearchClick = () => {
    setHasSearched(true);
    setCurrentPage(1);
    loadData(1, searchTextRef.current, startDateRef.current, endDateRef.current);
  };

  const handleUpdateSelectedHeaders = (keys: string[]) => {
    setSelectedHeaders(keys);
  };

  const handleDownloadTableData = async () => {
    if (downloading) return;
    
    setDownloading(true);
    try {
      let allItems: ScholarRecordWithFullName[] = [];
      let currentPage = 1;
      const pageSize = 100;
      let hasMoreData = true;

      while (hasMoreData) {
        const response = await searchScholars({
          keywords: searchText.trim() || undefined,
          start_date_input: startDate || undefined,
          end_date_input: endDate || undefined,
          skip: (currentPage - 1) * pageSize,
          limit: pageSize,
        });

        if (response.scholars && response.scholars.length > 0) {
          const transformedRecords = transformScholarRecords(response.scholars);
          allItems = [...allItems, ...transformedRecords];
          
          if (response.scholars.length < pageSize || allItems.length >= response.total) {
            hasMoreData = false;
          } else {
            currentPage++;
          }
        } else {
          hasMoreData = false;
        }
      }

      if (allItems.length > 0) {
        const headers = selectedHeaders.map(key => {
          const header = allHeaders.find(h => h.key === key);
          return header ? header.label : key;
        });

        const rows = allItems.map(scholar => 
          selectedHeaders.map(key => {
            let value: string | number | boolean | null | undefined;
            
            if (key === 'full_name') {
              value = scholar.full_name || '';
            } else {
              value = scholar[key as keyof ScholarRecordWithFullName];
            }
            
            if (value === null || value === undefined) {
              return '';
            }
            
            if (typeof value === 'boolean') {
              return value ? 'Yes' : 'No';
            }
            
            return String(value).replace(/"/g, '""');
          })
        );

        const csvContent = [
          headers.join(','),
          ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
        ].join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `scholar_table_data_${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
      }
    } catch (error) {
      console.error('Download failed:', error);
    } finally {
      setDownloading(false);
    }
  };

  if (!canViewScholarsDashboardContent) {
    return (
      <div className="flex-1 p-6 bg-gray-50 dark:bg-slate-900">
        <Headline 
          onDownload={handleDownloadTableData}
          downloading={downloading}
          hasData={scholars.length > 0}
        />
        <div className="mt-6 bg-white dark:bg-slate-800 rounded-lg shadow-sm border border-gray-200 dark:border-slate-700 p-8">
          <div className="text-center">
            <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 dark:bg-red-900">
              <svg className="h-6 w-6 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <h3 className="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">
              Access Denied
            </h3>
            <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
              You do not have permission to view the Scholars Dashboard content.
              Please contact your administrator.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <section className="flex-1 bg-white dark:bg-slate-900 overflow-y-auto font-poppins py-3 sm:py-6 transition-all duration-300">
      <Headline 
        onDownload={handleDownloadTableData}
        downloading={downloading}
        hasData={scholars.length > 0}
      />
      <div className="bg-white dark:bg-slate-800 mx-4 sm:mx-8 md:mx-12 my-6 sm:my-10 rounded-3xl shadow-xl border border-gray-200 dark:border-slate-700 overflow-hidden">
        <div className="px-4 sm:px-6 md:px-8 lg:px-10 py-4 sm:py-6 md:py-8 gap-3 sm:gap-4">
          <DashboardTabs
            searchText={searchText}
            setSearchText={setSearchText}
            onSearchClick={handleSearchClick}
            startDate={startDate}
            setStartDate={setStartDate}
            endDate={endDate}
            setEndDate={setEndDate}
          />
          {currentTab === 'table' && (
            <>
              <ColumnSelector
                allHeaders={allHeaders}
                selectedHeaders={selectedHeaders}
                updateSelectedHeaders={handleUpdateSelectedHeaders}
              />
              {loading ? (
                <div className="text-center py-56 text-gray-500 dark:text-gray-400 text-lg animate-pulse">
                  <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 dark:border-cyan-400 mb-4"></div>
                  <div>Loading scholar records...</div>
                </div>
              ) : scholars.length === 0 ? (
                <div className="flex flex-col items-center justify-center w-full py-48 text-gray-400 dark:text-gray-500">
                  <span className="text-6xl mb-6 text-blue-200 dark:text-cyan-900">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-16 h-16 mx-auto">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-3A2.25 2.25 0 008.25 5.25V9m10.5 0v10.125c0 1.012-.838 1.875-1.875 1.875H7.125A1.875 1.875 0 015.25 19.125V9m13.5 0H5.25m13.5 0a2.25 2.25 0 012.25 2.25v7.125A2.25 2.25 0 0118.75 20.25H5.25A2.25 2.25 0 013 18.375V11.25A2.25 2.25 0 015.25 9h13.5z" />
                    </svg>
                  </span>
                  <span className="italic text-sm sm:text-base md:text-lg text-center mb-6">
                    No scholar records found.
                  </span>
                  <button
                    className="px-6 py-3 bg-blue-600 dark:bg-cyan-700 text-white rounded-xl hover:bg-blue-700 dark:hover:bg-cyan-800 hover:shadow-lg transition-all duration-200 font-medium"
                    onClick={() => {
                      setSearchText('');
                      setStartDate('');
                      setEndDate('');
                      setHasSearched(false);
                      setCurrentPage(1);
                      loadData(1);
                    }}
                  >
                    Refresh Data
                  </button>
                </div>
              ) : (
                <Table
                  scholars={scholars}
                  selectedHeaders={selectedHeaders}
                />
              )}
              <Pagination
                currentPage={currentPage}
                setCurrentPage={setCurrentPage}
                totalCount={totalCount}
                pageSize={pageSize}
              />
            </>
          )}
          {currentTab === 'overview' && <Overview />}
        </div>
      </div>
    </section>
  );
};

export default MainContentSection;